package library.utils;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;
import android.view.WindowManager;

import java.lang.reflect.Method;

import library.logger.Logger;

/**
 * Created by Mr.Fan on 2015/12/16.
 */
public class DisplayUtil {

    private static Context context;

    private DisplayUtil() {

    }

    public static void init(@NonNull Context context) {
        DisplayUtil.context = context.getApplicationContext();
    }

    public static DisplayMetrics getMetrics() {
        return context.getResources().getDisplayMetrics();
    }

    public static int getActionBarHeight() {
        int actionBarHeight = 0;
        TypedValue typedValue = new TypedValue();
        if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValue, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(typedValue.data,
                    context.getResources().getDisplayMetrics());
        }
        return actionBarHeight;
    }

    private static int px2dp(float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int dp2px(float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2sp(float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public static int sp2px(float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int getStatusBarHeight() {
        // 获得状态栏高度
        int result = 0;
        try {
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = context.getResources().getDimensionPixelSize(resourceId);
            }
        } catch (Exception e) {
            Logger.debug(e);
        }
        return result;
    }

    public static int getNavigationBarHeight() {
        Resources res = context.getResources();
        boolean mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            if (hasNavBar()) {
                try {
                    String key;
                    if (mInPortrait) {
                        key = "navigation_bar_height";
                    } else {
                        key = "navigation_bar_height_landscape";
                    }
                    int resourceId = res.getIdentifier(key, "dimen", "android");
                    if (resourceId > 0) {
                        result = res.getDimensionPixelSize(resourceId);
                    }
                } catch (Exception e) {
                    Logger.debug(e);
                }
            }
        }
        return result;
    }

    private static boolean hasNavBar() {
        boolean hasNav = false;
        Resources res = context.getResources();
        String sNavBarOverride = null;
        try {
            Class c = Class.forName("android.os.SystemProperties");
            Method m = c.getDeclaredMethod("get", String.class);
            m.setAccessible(true);
            sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
        } catch (Throwable e) {
            sNavBarOverride = null;
        }
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            hasNav = res.getBoolean(resourceId);
            // check override flag (see static block)
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
        } else { // fallback
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                return !ViewConfiguration.get(context).hasPermanentMenuKey();
            }
        }
        return hasNav && !hasMenuOrBackBar(context);
    }

    public static boolean hasMenuOrBackBar(Context context) {
        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
        boolean hasMenuKey = ViewConfiguration.get(context)
                .hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap
                .deviceHasKey(KeyEvent.KEYCODE_BACK);

        if (!hasMenuKey && !hasBackKey) {
            // 做任何你需要做的,这个设备有一个导航栏
            return true;
        }
        return false;
    }

    public static int getAndroidAttr(int attr) {

        int minHeight = 0;
        TypedValue typedValue = new TypedValue();
        if (context.getTheme().resolveAttribute(attr, typedValue, true)) {
            minHeight = TypedValue.complexToDimensionPixelSize(typedValue.data, context.getResources().getDisplayMetrics());
        }
        return minHeight;
    }

    public static boolean isLargeInch() {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getMetrics(dm);
        double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
        double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
        // 屏幕尺寸
        double screenInches = Math.sqrt(x + y);
        // 大于6尺寸则为Pad
        if (screenInches >= 6.0) {
            return true;
        }
        return false;
    }

    public static boolean isLargeScreen() {
        return isLargeInch() &&
                (context.getResources().getConfiguration().screenLayout
                        & Configuration.SCREENLAYOUT_SIZE_MASK)
                        >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    public static int getListItemMinHeight() {
        boolean isLarge = DisplayUtil.isLargeScreen();
        int attr = isLarge ? android.R.attr.listPreferredItemHeight : android.R.attr.listPreferredItemHeightSmall;
        int minHeight = DisplayUtil.getAndroidAttr(attr);
        return minHeight;
    }
}